package team.kirohuji.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import team.kirohuji.domain.User;

/**
 * Shiro工具类
 * 
 * @author kirohuji
 *
 */
public class ShiroUtils {
	/**
	 * 
	 * 获取shiro session
	 * 
	 * @return Session
	 */
	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	/**
	 * 获取shiro 身份信息
	 * 
	 * @return Subject
	 */
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	/**
	 * 获取当前登录人 user
	 * 
	 * @return SystemUser
	 */
	public static User getUserEntity() {
		return (User) getSession().getAttribute("user");
	}

	/**
	 * 获取当前登录人的ID
	 * 
	 * @return Integer
	 */
	public static Integer getUserId() {

		return getUserEntity().getUserId();
	}

	/**
	 * 设置session
	 * 
	 * @param key
	 *            键
	 * @param value
	 *            值
	 */
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	/**
	 * 从session里获取值
	 * 
	 * @param key
	 *            键
	 * @return Object
	 */
	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	/**
	 * shiro 退出登录
	 * 
	 */
	public static void logout() {

		SecurityUtils.getSubject().logout();
	}

	/**
	 * shiro 提供加密算法
	 * 
	 * @param txt
	 *            明文
	 * @param salt
	 *            干扰字符串，可以为null
	 * @return String
	 */
	public static String MD5(String txt, String salt) {

		return new SimpleHash("md5", txt, ByteSource.Util.bytes(salt), 252).toHex();
	}

	/*
	 * public static void main(String[] args) {
	 * 
	 * RandomNumberGenerator randomNumberGenerator = new
	 * SecureRandomNumberGenerator(); String dd =
	 * randomNumberGenerator.nextBytes().toHex() + "18616909203";
	 * System.out.println(dd);
	 * 
	 * System.out.println(MD5("123456", dd)); }
	 */
}